﻿using Infrastructure.DbUtility;
using Infrastructure.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Script.Serialization;

public partial class admin_chapter_edit : BasePage
{
    protected int chapterId
    {
        get { return ViewState["Chapter_Id"] == null ? 0 : (int)ViewState["Chapter_Id"]; }
        set { ViewState["Chapter_Id"] = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            int cid = 0;
            int.TryParse(Request["cid"], out cid);
            chapterId = cid;

            this.InitChapterData(cid);
        }
        if (Request["do"] == "add-video")
        {
            List<DataRow> fileRows = new List<DataRow>();
            UploadHelper helper = new UploadHelper();
            foreach (string f in Request.Files) fileRows.Add(helper.Upload(Request.Files[f], true));
            var data = this.AddVideos(fileRows);
            Response.Clear();
            Response.Write(new JavaScriptSerializer().Serialize(new { success = true, data = data }));
            Response.End();
        }
        if (Request["save"] == "basic")
        {
            this.SaveBasic();
        }
    }

    private object AddVideos(List<DataRow> fileRows)
    {
        var files = fileRows.Select(r => r.Value("fileid")).ToArray();

        string title = "未命名视频";
        string description = string.Empty;
        decimal creator = 1;

        string sql = "DECLARE @cname nvarchar(50),@max_vid int "
                       + "SELECT @cname = '',@max_vid = 0 "
                       + "SELECT @cname = '' FROM Chapter (NOLOCK) WHERE cid = {0} "
                       + "SELECT @max_vid = MAX(vid) FROM Video (NOLOCK) "
                       + "INSERT INTO Video (title,cid,cname,[description],aid,creator) "
                       + "SELECT [name],{0}, @cname,{1},aid,{2} "
                       + "FROM Attachment (NOLOCK) WHERE aid IN ('" + string.Join("','", files) + "') "
                       + "SELECT A.*,B.fullPath href,'' thumbnail FROM Video A (NOLOCK) LEFT JOIN Attachment B (NOLOCK) ON A.aid = B.aid WHERE A.vid > ISNULL(@max_vid,0)";
        DbHelper db = new DbHelper();
        var table = db.ExecQueryEx(sql, chapterId, description, creator);
        return table.AsEnumerable().Select(r => new { vid = r.Value<int>("vid"), href = r.Value("href").Replace(Server.MapPath("~"), "/"), thumbnail = "/content/images/video-128.png", title = r.Value("title") }).ToArray();
    }

    private void InitChapterData(int cid)
    {
        DbHelper db = new DbHelper();
        string sql = "SELECT * FROM Chapter (NOLOCK) WHERE cid = " + cid;
        DataTable tbChapter = db.ExecQuery(sql);
        if (tbChapter != null && tbChapter.Rows.Count > 0)
        {
            foreach (DataColumn col in tbChapter.Columns) Entity[col.ColumnName] = tbChapter.Rows[0][col];

            sql = "SELECT a.*,b.fullPath FROM Video a (NOLOCK) LEFT JOIN  Attachment b (NOLOCK) ON a.aid = b.aid WHERE a.cid = " + cid;
            DataTable bt = db.ExecQueryEx(sql);
            object[] videos = new object[bt.Rows.Count];
            for (int i = 0; i < bt.Rows.Count; i++)
            {
                videos[i] = new { vid = bt.Rows[i]["vid"], href = base.GetSitePath(bt.Rows[i]["fullPath"].ToStringEx()), thumbnail = "/content/images/video-128.png", title = bt.Rows[i]["title"] };
            }
            this.lstVideo.DataSource = videos;
            this.lstVideo.DataBind();
            //0 单选 1 多选 2 填空 3 简答
            sql = "SELECT *, (CASE type WHEN 0 THEN '单选' WHEN 1 THEN '多选' WHEN 2 THEN '填空' WHEN 3 THEN '简答' ELSE '' END) typeName "
                 + "FROM Question A (NOLOCK) WHERE qid IN (SELECT AA.qid FROM PracticeQuestion AA WHERE AA.pid = {0})";
            DataTable tbQuestions = db.ExecQueryEx(sql, tbChapter.Rows[0].Value<decimal>("pid"));

            sql = "SELECT * FROM QuestionOption (NOLOCK) WHERE pid IN (SELECT A.qid FROM Question A (NOLOCK) WHERE qid IN (SELECT AA.qid FROM PracticeQuestion AA WHERE AA.pid = {0}))";
            DataTable tbOptions = db.ExecQueryEx(sql, tbChapter.Rows[0].Value<decimal>("pid"));

            tbQuestions.Columns.Add("answers");
            foreach (DataRow row in tbQuestions.Rows)
            {
                var options = tbOptions.Select("answer = right AND pid = " + row.Value<decimal>("qid")).Select(r => r.Value("answer"));
                row["answers"] = string.Join(",", options);
            }
            lstQuestion.DataSource = tbQuestions;
            lstQuestion.DataBind();
        }




    }

    private void SaveBasic()
    {
        var title = Request["title"];
        var content = Request["content"];

        string sql = "UPDATE  Chapter SET title = {0}, content = {1} WHERE cid = {2}";
        DbHelper db = new DbHelper();
        db.ExecuteUpdateEx(sql, title, content, chapterId);

        Response.Clear();
        Response.Write("{\"success\":true}");
        Response.End();
    }

    protected void btnNavigate_Click(object sender, EventArgs e)
    {
        string sindex = Request["txtGoTo"];
        int index = 0;
        if (!int.TryParse(sindex, out index) || index < 1) return;

        //var keyword = txtName.Text.Trim();
        //var nid = int.Parse("0" + txtGradeId.Value);
        this.Index = index;

        //this.LoadGrade(index, keyword, nid);
    }
}